<template>
	<view class="address">
		<view v-for="item in addressList" :key="item.id" class="ad-item">
			<ad-card :row="item" @change-address="handleChangeAddress" @delete="handleDeleteAddress" />
		</view>
		<view class="plus-address">
				<button class="btn-primary block" @click="handlePlusAddress">新增地址</button>
		</view>
	</view>
</template>

<script>
import AddressCard from '@/components/address-card/address-card.vue';
export default {
	components: {
		'ad-card': AddressCard
	},
	data() {
		return {
			addressList: []
		};
	},
	onReady() {
		this.getAddressList()
	},
	onShow() {
		this.getAddressList()
	},
	methods: {
		// 改变默认地址
		handleChangeAddress(row) {
			this.$request.address.updateDefault({id: row.id}).then(res => {
				if(res.status === 200) {
					this.getAddressList()
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				}
			}).catch(() =>{
				uni.showToast({
					title:'服务器出错了',
					icon: 'none'
				})
			})
		},
		// 获取地址列表
		getAddressList() {
			this.$request.address.queryAddressList().then(res => {
				if(res.status === 200) {
					this.addressList = res.data
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				}
			}).catch(() => {
				uni.showToast({
					title: '服务器出错了',
					icon:'none'
				})
			})
		},
		// 删除当前地址
		handleDeleteAddress(row) {
			uni.showLoading()
			// this.addressList = this.addressList.filter(item => item.id !== row.id)
			this.$request.address.removeAddress({id: row.id}).then(res => {
				uni.hideLoading()
				if(res.status === 200) {
					uni.showToast({
						title: '删除成功',
						icon: 'none'
					})
					this.getAddressList()
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				}
			}).catch(() =>{
				uni.hideLoading()
				uni.showToast({
					title: '服务器出错了',
					icon: 'none'
				})
			})
		},
		// 新增地址
		handlePlusAddress() {
			uni.navigateTo({
				url: '/pages/address/create/create'
			})
		}
	}
};
</script>

<style lang="scss" scoped>
.address {
	min-height: 100vh;
	padding: 20rpx;
	background: $cu-bg;
	box-sizing: border-box;
	.ad-item {
		margin-bottom: 20rpx;
	}
	.plus-address {
		padding: 20rpx;
	}
}
</style>
